package com.cyzy.controller;

import com.cyzy.dto.AlipayPaymentRequest;
import com.cyzy.dto.SimplePaymentRequest;
import com.cyzy.service.AlipayService;
import com.cyzy.utils.OrderUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付控制器
 * @author LIGHT
 */
@Slf4j
@RestController
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    /**
     * 创建支付订单（完整版）
     * @param paymentRequest 支付请求参数
     * @return 支付页面URL或错误信息
     */
    @PostMapping("/createPayment")
    public ResponseEntity<Map<String, Object>> createPayment(@Validated @RequestBody AlipayPaymentRequest paymentRequest) {
        Map<String, Object> result = new HashMap<>();

        try {
            log.info("开始创建支付订单，用户ID：{}，订单号：{}，金 额：{}",
                    paymentRequest.getUserId(), paymentRequest.getOrderNo(), paymentRequest.getAmount());
            
            String paymentUrl = alipayService.createPayment(paymentRequest);
            
            result.put("code", 200);
            result.put("message", "支付订单创建成功");
            result.put("data", paymentUrl);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("创建支付订单失败：", e);
            result.put("code", 500);
            result.put("message", "创建支付订单失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 创建支付订单（简化版 - 前端只需传用户ID和金额）
     * @param simpleRequest 简化支付请求参数
     * @return 支付页面URL或错误信息
     */
    @PostMapping("/pay")
    public ResponseEntity<Map<String, Object>> createSimplePayment(@Validated @RequestBody SimplePaymentRequest simpleRequest) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("开始创建简化支付订单，用户ID：{}，金额：{}", 
                    simpleRequest.getUserId(), simpleRequest.getAmount());
            
            // 自动生成订单号和订单ID
            String orderNo = OrderUtils.generateAlipayOrderNo(simpleRequest.getUserId());

            // 使用更小的整数值作为订单ID，避免数据库整数溢出
            int orderId = (int)(System.currentTimeMillis() % Integer.MAX_VALUE);
            
            // 转换为完整请求对象
            AlipayPaymentRequest paymentRequest = new AlipayPaymentRequest();
            paymentRequest.setUserId(simpleRequest.getUserId());



            paymentRequest.setOrderId((long)orderId);

            paymentRequest.setOrderNo(orderNo);
            paymentRequest.setAmount(simpleRequest.getAmount());
            paymentRequest.setSubject(simpleRequest.getSubject());
            
            String paymentUrl = alipayService.createPayment(paymentRequest);
            
            result.put("code", 200);
            result.put("message", "支付订单创建成功");
            result.put("data", Map.of(
                    "paymentUrl", paymentUrl,
                    "orderNo", orderNo,
                    "orderId", orderId
            ));
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("创建简化支付订单失败：", e);
            result.put("code", 500);
            result.put("message", "创建支付订单失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 支付宝异步回调接口
     * @param request HTTP请求
     * @return success或failure
     */
    @PostMapping("/notify")
    public String paymentNotify(HttpServletRequest request) {
        log.info("收到支付宝异步回调");
        return alipayService.handlePaymentNotify(request);
    }

    /**
     * 支付宝同步回调接口（用户支付完成后的跳转页面）
     * @param request HTTP请求
     * @param response HTTP响应
     */
    @GetMapping("/return")
    public void paymentReturn(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("收到支付宝同步回调");
        
        // 获取支付宝返回的参数
        String outTradeNo = request.getParameter("out_trade_no");
        String tradeNo = request.getParameter("trade_no");
        String totalAmount = request.getParameter("total_amount");
        
        log.info("同步回调参数 - 订单号：{}，支付宝交易号：{}，金额：{}", outTradeNo, tradeNo, totalAmount);
        
        // 重定向到前端页面，可以携带参数

        response.sendRedirect("http://localhost:50000/#/pages/my/purse?orderNo=" + outTradeNo + "&amount=" + totalAmount);


    }

    /**
     * 查询支付状态
     * @param orderNo 订单号
     * @return 支付状态
     */
    @GetMapping("/status/{orderNo}")
    public ResponseEntity<Map<String, Object>> getPaymentStatus(@PathVariable String orderNo) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 这里可以根据订单号查询支付状态
            // 暂时返回成功状态，实际项目中需要查询数据库
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", Map.of("orderNo", orderNo, "status", "待查询"));
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("查询支付状态失败：", e);
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
} 